package com.gimi.cloud.jimi.queue.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoLogDao;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import com.gimi.cloud.jimi.dto.app.moreInfo.FengchaoEmailDTO;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoLogEntity;
import com.gimi.cloud.jimi.entity.user.User;
import com.gimi.cloud.jimi.queue.service.FengchaoCreditCardEmailService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @auther loongs
 * @date 2018/1/15  16:00
 */
@Service
public class FengchaoCreditCardEmailServiceImpl implements FengchaoCreditCardEmailService {

    private static final Logger log = LoggerFactory.getLogger(FengchaoCreditCardEmailServiceImpl.class);
    private IRedisService iRedisService;
    private InterfacePlatformRequestService ipRequestService;
    private MoreInfoDao moreInfoDao;
    private MoreInfoLogDao moreInfoLogDao;
    private UserDao userDao;
    private SysConfigDao sysConfigDao;
    //最大容错次数暂时定为3次
    private final Integer MAXTIMES = 3;

    private final static String INTERFACE_PLATFORM_UNIVERSAL_CREDITCARDEMAIL = "interface_platform_universal_creditCardEmail";

    @Autowired
    public FengchaoCreditCardEmailServiceImpl(IRedisService iRedisService, InterfacePlatformRequestService ipRequestService,
                                              MoreInfoDao moreInfoDao, UserDao userDao, SysConfigDao sysConfigDao,MoreInfoLogDao moreInfoLogDao) {
        this.iRedisService = iRedisService;
        this.ipRequestService = ipRequestService;
        this.moreInfoDao = moreInfoDao;
        this.userDao = userDao;
        this.sysConfigDao = sysConfigDao;
        this.moreInfoLogDao= moreInfoLogDao;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void getReport(Message message, Channel channel, FengchaoEmailDTO fengchaoEmailDTO) throws Exception {

        log.info("验证参数");
        if (fengchaoEmailDTO == null || StringUtil.isBlank(fengchaoEmailDTO.getUserId()) || StringUtil.isBlank(fengchaoEmailDTO.getAppemailkey())) {
            throw new MsgException(ResponseCodeEnum.CREDITCARDEMAIL_IS_NOT_FOUND);
        }
        User user = userDao.getUserByUserId(fengchaoEmailDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过信用卡邮箱账单，需要获取状态为获取中
        MoreInfoEntity moreInfoEntity = moreInfoDao.getMoreInfoByUserIdAndTypeAndData(fengchaoEmailDTO.getUserId(),5,1);
        if (moreInfoEntity == null || moreInfoEntity.getGetdataErrorTimes() >= MAXTIMES) {
            throw new MsgException(ResponseCodeEnum.CREDITCARDEMAIL_DATA_ERROR_TIMES_IS_OUT_OF_TIMES);
        }

        log.info("读取数据库配置配置表");
        String fengchao_creditCardEmail = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_CREDITCARDEMAIL);
        JSONObject feJson = JSON.parseObject(fengchao_creditCardEmail);

        log.info("封装查询状态的参数json");
        JSONObject emailStatus = feJson.getJSONObject("fengchao_creditCard_email_status");
        JSONObject statusBody = emailStatus.getJSONObject("body");
        statusBody.put("appemailkey", fengchaoEmailDTO.getAppemailkey());

        emailStatus.put("body",statusBody);
        String statusRes = ipRequestService.sendApiPost(emailStatus.toJSONString());
        JSONObject statusResJson = JSON.parseObject(statusRes);
        JSONObject statusResBody = statusResJson.getJSONObject("body");
        String errors = statusResBody.getString("message");
        //新建日志记录
        MoreInfoLogEntity moreInfoLogEntity =new MoreInfoLogEntity();
        moreInfoLogEntity.setUserId(user.getUserId());
        moreInfoLogEntity.setType("5");
        moreInfoLogEntity.setAddTime(DateUtil.getNow());
        //先存入查询状态的请求参数和返回参数，如果状态为1000，再修改为抓取资料的请求参数和返回参数
        moreInfoLogEntity.setResponseData(statusRes);
        moreInfoLogEntity.setRequestData(emailStatus.toJSONString());

        if (statusResBody != null && "300".equals(statusResBody.getString("messageType"))) {
            channel.abort();
        } else if ("1000".equals(statusResBody.getString("messageType"))) {

            log.info("开始蜂巢信用卡邮箱账单接口");
            log.info("封装抓取数据的参数json");
            JSONObject obtainbills = feJson.getJSONObject("fengchao_creditCard_email_obtainbills");

            JSONObject body = obtainbills.getJSONObject("body");
            body.put("appemailkey", fengchaoEmailDTO.getAppemailkey());
            //可不传
            body.put("lastTime", "");

            obtainbills.put("body", body);
            log.info("拼接请求参数：" + obtainbills);
            log.info("发起请求获取信用卡邮箱账单开始");
            String sendApiPost = ipRequestService.sendApiPost(obtainbills.toJSONString());

            JSONObject reportJson = JSON.parseObject(sendApiPost);
            JSONObject reportbody = reportJson.getJSONObject("body");
            JSONObject data = reportbody.getJSONObject("data");
            String type = reportbody.getString("type");

            //存入日志
            moreInfoLogEntity.setResponseData(sendApiPost);
            moreInfoLogEntity.setRequestData(obtainbills.toJSONString());

            //只有type为1的时候为成功，其他情况都是失败
            if (reportbody != null && "1".equals(type) ) {
                //存入数据
                moreInfoEntity.setReportData(data.getString("ossUrl"));
                moreInfoEntity.setGetdata("2");
                moreInfoEntity.setGetdataTime(DateUtil.getNow());
                moreInfoEntity.setGetdataErrorTimes(0);
                //TODO 有效时长，等风控规则
                moreInfoEntity.setReportEffectionBegin(DateUtil.getNow());
                moreInfoEntity.setReportEffectionEnd(DateUtil.getLateYear(1));
                moreInfoEntity.setBaRemark("");

                //抓取状态（1成功，2失败）
                moreInfoLogEntity.setStatus(1);
            } else {
                moreInfoEntity.setGetdata("3");
                moreInfoEntity.setGetdataErrorTimes(moreInfoEntity.getGetdataErrorTimes() + 1);

                //抓取状态（1成功，2失败）
                moreInfoLogEntity.setStatus(2);
            }

        } else {
            moreInfoEntity.setGetdata("3");
            moreInfoEntity.setGetdataErrorTimes(moreInfoEntity.getGetdataErrorTimes() + 1);
            moreInfoEntity.setBaRemark(errors);

            //抓取状态（1成功，2失败）
            moreInfoLogEntity.setStatus(2);
            moreInfoLogEntity.setRemark(errors);
        }
        //现存日志
        moreInfoLogDao.insertSelective(moreInfoLogEntity);

        moreInfoEntity.setUpdateUid(user.getUserId());
        moreInfoEntity.setUpdateUname(user.getAddUname());
        moreInfoEntity.setUpdateTime(DateUtil.getNow());
        moreInfoDao.updateByPrimaryKey(moreInfoEntity);
        log.info("发起请求获取信用卡邮箱账单结束");

    }
}
